//
//  COCallStatusView.swift
//  CocoProject
//
//  Created by Vill on 2023/11/15.
//

import UIKit
import AVKit

// type 1:拒绝来电 2:接听来电 3:挂断拨打电话
typealias callStatusBlock = (_ type:Int)->Void

class COCallStatusView: UIView {

    var callBolck:callStatusBlock?
    var player = AVPlayer()
    var playerLayer = AVPlayerLayer()
    
    // 容器
    lazy var iconBgView: UIImageView = {
        let bg = UIImageView()
        bg.image = KImaged("coco_main_bg")
        bg.contentMode = .scaleAspectFill
        return bg
    }()

    lazy var iconImg: UIImageView = {
        let icon = UIImageView()
        icon.contentMode = .scaleAspectFill
        icon.layer.cornerRadius = PTW(150/2)
        icon.clipsToBounds = true
        return icon
    }()
    
    // 昵称
    lazy var nameLbl: UILabel = {
        let name = UILabel()
        name.textColor = UIColor.colorWithHex("#2C255B")
        name.font = UIFont.pingfangFont(ofSize: PTW(20), weight: .medium)
        return name
    }()
    
    // 价格
    lazy var priceLbl: UILabel = {
        let price = UILabel()
        price.textColor = UIColor.colorWithHex("#2C255B")
        price.font = UIFont.pingfangFont(ofSize: PTW(15), weight: .medium)
        let feed = kFeedbackVer.keyGetNSDefaultsKey() as? Bool
        price.isHidden = feed == true
        return price
    }()
    
    // 拒绝来电
    lazy var refause: UIButton = {
        let i = UIButton()
        i.setImage(KImaged("coco_video_refause"), for: .normal)
        i.isHidden = true
        i.addTarget(self, action: #selector(refauseaction), for: .touchUpInside)
        return i
    }()
    
    // 接听来电
    lazy var accept: UIButton = {
        let i = UIButton()
        i.setImage(KImaged("coco_video_accept"), for: .normal)
        i.isHidden = true
        i.addTarget(self, action: #selector(acceptAction), for: .touchUpInside)
        return i
    }()
    
    // 挂断来电
    lazy var hangUp: UIButton = {
        let i = UIButton()
        i.setImage(KImaged("coco_video_refause"), for: .normal)
        i.isHidden = true
        i.addTarget(self, action: #selector(hangUpaction), for: .touchUpInside)
        return i
    }()
    
    @objc func refauseaction(){
        if self.callBolck != nil{
            self.callBolck!(1)
        }
    }
    
    @objc func acceptAction(){
        if self.callBolck != nil{
            self.callBolck!(2)
        }
    }

    @objc func hangUpaction(){
        if self.callBolck != nil{
            self.callBolck!(3)
        }
    }

    // 拨打状态
    lazy var statusLbl: UILabel = {
        let status = UILabel()
        status.textColor =  UIColor.colorWithHex("#7863A6", 0.3)
        status.font = UIFont.pingfangFont(ofSize: PTW(13), weight: .medium)
        status.textAlignment = .center
        status.numberOfLines = 0
        return status
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.white
        addUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func addUI(){
        addSubview(iconBgView)
        addSubview(iconImg)
        addSubview(nameLbl)
        addSubview(priceLbl)
        addSubview(hangUp)
        addSubview(refause)
        addSubview(accept)
        addSubview(statusLbl)
        iconBgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        iconImg.snp.makeConstraints { make in
            make.size.equalTo(PTW(150))
            make.centerX.equalTo(iconBgView)
            make.top.equalToSuperview().offset(PTW(140))
        }
        nameLbl.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(iconImg.snp.bottom).offset(PTW(10))
            make.height.equalTo(PTW(22))
        }
        priceLbl.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(nameLbl.snp.bottom)
            make.height.equalTo(PTW(16))
        }
        hangUp.snp.makeConstraints { make in
            make.size.equalTo(PTW(80))
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-PTW(150))
        }
        refause.snp.makeConstraints { make in
            make.size.equalTo(PTW(80))
            make.centerY.equalTo(hangUp)
            make.trailing.equalTo(hangUp.snp.leading).offset(-PTW(3))
        }
        accept.snp.makeConstraints { make in
            make.size.equalTo(PTW(80))
            make.centerY.equalTo(hangUp)
            make.leading.equalTo(hangUp.snp.trailing).offset(PTW(3))
        }
        statusLbl.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(PTW(25))
            make.trailing.equalToSuperview().offset(-PTW(25))
            make.top.equalTo(hangUp.snp.bottom).offset(PTW(25))
        }
    }
    
    deinit{
        print("销毁了--------callstatus")
    }
}

extension COCallStatusView{
    // 设置用户信息和拨打界面展示
    func setUserInfo(model:DGChatUserInfoModel,iscalling:Bool){
        
        self.iconImg.sd_setUrlImage(model.profilePhoto, placeholder: KImaged("coco_icon_holder"))
        self.nameLbl.text = model.name
        let feed = kFeedbackVer.keyGetNSDefaultsKey() as? Bool
        self.priceLbl.attributedText = "\(model.price)/min".stringWithImage(img: "coco_mine_star", bounds: CGRect(x: 0, y: -PTW(2) , width: PTW(12) , height: PTW(12)),isFirst: true)
        if (feed == false){
            self.priceLbl.isHidden = false
        }else{
            self.priceLbl.isHidden = true
        }
        if iscalling{
            self.statusLbl.text = "Video call…"
            self.hangUp.isHidden = false
            self.refause.isHidden = true
            self.accept.isHidden = true
        }else{
            self.statusLbl.text = "This is an encrypted call. We guarantee none of your information will be recorded or saved. Please enjoy this Call."
            self.hangUp.isHidden = true
            self.refause.isHidden = false
            self.accept.isHidden = false
        }
        
        if (model.summary?.isEmptyStr == false && feed == false){
            self.iconImg.isHidden = true
            let url = URL(string: model.summary!)
            self.player = AVPlayer(url: url!)
            self.player.volume = 0
            self.playerLayer = AVPlayerLayer(player: self.player)
            self.playerLayer.frame = UIScreen.main.bounds
            self.playerLayer.videoGravity = .resizeAspectFill
            self.layer.insertSublayer(self.playerLayer, above: self.iconImg.layer)
//            self.layer.insertSublayer(self.playerLayer, at: 0)
            self.player.play()
            NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(avPlayerItemDidPlayToEndTime), name: .AVPlayerItemDidPlayToEndTime, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
        }
    }
    
    @objc private func applicationDidBecomeActive(noti: Notification) {
        self.player.play()
    }

    @objc private func applicationWillResignActive(noti: Notification) {
        self.player.pause()
    }

    @objc private func avPlayerItemDidPlayToEndTime(noti: Notification) {
        self.player.seek(to: CMTime(value: 0, timescale: 1))
        self.player.play()
    }
}
